package com.digiregistry.api.wrapper.converters;

import java.util.LinkedHashMap;
import java.util.Map;

import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;

public class StringMapConverter implements Converter {

	public boolean canConvert(Class type) {
		return Map.class.isAssignableFrom(type);
	}

	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
		Map<String, String> map = (Map<String, String>)source;
		for (Map.Entry<String, String> entry : map.entrySet()) {
			writer.startNode(entry.getKey().toString());
			context.convertAnother(entry.getValue());
			writer.endNode();
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		Map<String, String> map = new LinkedHashMap<String, String>();
		while (reader.hasMoreChildren()) {
			reader.moveDown();
			map.put(reader.getNodeName(), reader.getValue());
			reader.moveUp();
		}
		return map;
	}

}
